from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import os
from Utility import VIEW_PATH
from Utility import SessionKey
from Utility import UserRole
from Utility import IsEmptyString
from Configuration import DEFAULT_VIEW_SUFFIX
from gaesessions import get_current_session
from Utility import ViewName
from Utility import TemplateValueName
import Configuration
from urllib import quote 


class BaseController(webapp.RequestHandler):
    def Render(self, viewName, template_values):
        """
        Render HTML and return to User. 
            This method will make sure the view name is ended with '.html'
            Content-Type is set to 'text/html'
        """
        if not viewName.endswith(DEFAULT_VIEW_SUFFIX):
            viewName += DEFAULT_VIEW_SUFFIX
        path = os.path.join(VIEW_PATH, viewName)
        self.response.headers['Content-Type'] = 'text/html'
        
        if template_values is None:
            template_values = {}
            
        username = self.GetCurrentUser()
        if username is None:
            template_values["hasLogin"] = False
        else:
            template_values["hasLogin"] = True
            template_values["username"] = username.DisplayName
        
        self.response.out.write(template.render(path, template_values))

    def DeleteCurrentSession(self):
        """
        terminate current session
        """
        session = get_current_session()
        if session.is_active():
            if self.GetCurrentUser() is not None:
                self.response.headers.add_header('Set-Cookie', 'authn=%s; expires=Fri, 31-Dec-2000 23:59:59 GMT' % (""))
                session.terminate(True)

    def GetCurrentUser(self):
        """
        return current user in session or none
        """
        session = get_current_session()
        return session.get(SessionKey.CURRENT_USER, None)
    
    def GetSessionItem(self, sessionKey):
        """
        return session object in session or none
        """
        session = get_current_session()
        return session.get(sessionKey, None)
    
    def SetSessionItem(self, sessionKey, obj):
        """
        Store object in session
        """
        if sessionKey is not None:
            session = get_current_session()
            session[sessionKey] = obj
    
    
    def VerifyCurrentUserRole(self, user, uRole=UserRole.SystemAdmin, reURL="/"):
        """
        Verify Current Login User is specified role, return True/False
        If user has not login, then return False 
        """
        try:
            if user is not None:
                if user.Role == uRole:
                    return True
                else:                    
                    self.Return403(reURL)
                    return False
        except:
            # do nothing
            pass
        
        if user is None and not IsEmptyString(reURL):
            self.redirect(Configuration.DEFAULT_LOGINSUCCESS_REDIRECT + quote(reURL))
        return False
        
    def Return403(self, message=""):
        self.response.set_status(403)
        template_values = {TemplateValueName.ERROR_MESSAGE: message}
        return self.Render(ViewName.FORBIDDENPAGE, template_values) 
    
    
